package com.pubg.dao.impl;

import com.pubg.dao.BaseDao;
import com.pubg.dao.UserDao;
import com.pubg.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 用户数据访问接口实现类
 */
public class UserDaoImpl extends BaseDao implements UserDao {

    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;
    @Override
    public int add(User user) {
        String sql = "INSERT INTO user_account VALUES(0,?,?,?,?,?,?,?,?,?)";
        return executeUpdate(sql,
                user.getLoginName(),
                user.getPassword(),
                user.getType(),
                user.getUserName(),
                user.getGender(),
                user.getAddress(),
                user.getTelephone(),
                user.getBirthday(),
                user.getEmail()
                );
    }

    @Override
    public User login(String uname, String upwd) {
        User user = null;
        String sql = "SELECT id,loginName,type,userName,gender,address,telephone,birthday,email FROM user_account" +
                " WHERE loginName=? AND `password`=?";
        try {
            conn = openConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,uname);
            pstmt.setString(2,upwd);
            rs = pstmt.executeQuery();
            if (rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setLoginName(rs.getString("loginName"));
                user.setType(rs.getInt("type"));
                user.setUserName(rs.getString("userName"));
                user.setGender(rs.getInt("gender"));
                user.setAddress(rs.getString("address"));
                user.setTelephone(rs.getString("telephone"));
                user.setBirthday(rs.getTimestamp("birthday"));
                user.setEmail(rs.getString("email"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(rs,pstmt,conn);
        }
        return user;
    }

    @Override
    public int findByName(String loginName) {
        User user = null;
        String sql = "SELECT COUNT(1) count FROM user_account WHERE loginName=? ";
        try {
            conn = openConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,loginName);
            rs = pstmt.executeQuery();
            if (rs.next()){
                return rs.getInt("count");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(rs,pstmt,conn);
        }
        return 0;
    }
}
